package com.aaa.Filter;

import com.aaa.exception.OAuthAuthenticationEntryPoint;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.exceptions.BadClientCredentialsException;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//拦截某个路径
public class OauthClientCredentialsTokenEndpointFilter extends ClientCredentialsTokenEndpointFilter {

   private AuthenticationEntryPoint authenticationEntryPoint ;
   private AuthorizationServerSecurityConfigurer configuration;
    //构造方法

    public OauthClientCredentialsTokenEndpointFilter(AuthenticationEntryPoint authenticationEntryPoint, AuthorizationServerSecurityConfigurer configuration) {
        this.authenticationEntryPoint = authenticationEntryPoint;
        this.configuration = configuration;
    }

    @Override
    protected AuthenticationManager getAuthenticationManager() {
        return configuration.and().getSharedObject(AuthenticationManager.class);
    }

    @Override
    public void afterPropertiesSet() {
        //认证失败处理器
        this.setAuthenticationFailureHandler(new AuthenticationFailureHandler() {
            public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
                Class<? extends AuthenticationException> aClass = exception.getClass();
                System.out.println(aClass);
                if (exception instanceof BadCredentialsException) {
                    exception = new BadCredentialsException(((AuthenticationException)exception).getMessage(), new BadClientCredentialsException());
                }
                //处理结果
                authenticationEntryPoint.commence(request,response,exception);
            }
        });
        //认证成功处理器
        this.setAuthenticationSuccessHandler(new AuthenticationSuccessHandler() {
            public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
            }
        });
    }
}
